<!-- 童晓白修改 2025-08-16 14:00-->
<template>
  <view class="publish-task-page">
    <!-- 简化动态背景 -->
    <view class="background">
      <view class="bubbles">
        <view class="bubble" v-for="n in 3" :key="n"></view>
      </view>
    </view>

    <view class="container">
      <!-- 发布任务表单 -->
      <view class="publish-form">
        <text class="page-title">{{ isEditMode ? '修改任务' : '发布任务' }}</text>

        <view class="form-group">
          <label>任务名称（原始内容）<text class="required">*</text></label>
          <input type="text" v-model="originalTaskName" required class="form-input" @input="onOriginalContentChange" />
          <view class="hint-text">请输入您的原始任务标题</view>
        </view>

        <view class="form-group" v-if="!isContentOptimized">
          <button class="optimize-btn" @click="optimizeContent" :disabled="isOptimizing || !originalTaskName || !originalTaskRequirements">
            <span v-if="isOptimizing">优化中...</span>
            <span v-else>✨ AI优化内容</span>
          </button>
          <view class="hint-text" style="color: #ff9800; margin-top: 8px;">
            ⚠️ 必须使用AI优化后的内容才能发布任务
          </view>
        </view>

        <view class="form-group" v-if="isContentOptimized">
          <label>优化后的任务名称 <text class="required">*</text></label>
          <input type="text" v-model="taskName" required class="form-input optimized-input" />
          <view class="hint-text" style="color: #4caf50;">✓ 已优化（可编辑）</view>
          <button class="re-optimize-btn" @click="optimizeContent" :disabled="isOptimizing">
            <span v-if="isOptimizing">重新优化中...</span>
            <span v-else>🔄 重新优化</span>
          </button>
        </view>

        <view class="form-group">
          <label>任务详细功能要求（原始内容）<text class="required">*</text></label>
          <textarea v-model="originalTaskRequirements" rows="4" required class="form-textarea" @input="onOriginalContentChange"></textarea>
          <view class="hint-text">请输入您的原始任务描述</view>
        </view>

        <view class="form-group" v-if="isContentOptimized">
          <label>优化后的任务详细功能要求 <text class="required">*</text></label>
          <textarea v-model="taskRequirements" rows="4" required class="form-textarea optimized-input"></textarea>
          <view class="hint-text" style="color: #4caf50;">✓ 已优化（可编辑）</view>
        </view>

        <view class="form-group">
          <label>截止日期 <text class="required">*</text></label>
          <!-- #ifdef H5 -->
          <input type="date" v-model="taskDeadline" :min="minDate" required class="form-input" />
          <!-- #endif -->
          <!-- #ifdef MP-WEIXIN || APP-PLUS -->
          <picker mode="date" :value="taskDeadline" :start="minDate" @change="onDateChange" class="form-picker">
            <view class="picker-display">{{ taskDeadline || '请选择截止日期' }}</view>
          </picker>
          <!-- #endif -->
        </view>

        <view class="form-group">
          <label>任务相关图片</label>
          <view class="image-upload-container">
            <!-- #ifdef H5 -->
            <view class="image-upload-area" @click="triggerImageUpload" @dragover.prevent @drop.prevent="handleDrop">
              <input type="file" ref="imageInput" accept="image/*" multiple class="hidden" @change="handleImageUpload" />
              <view class="upload-placeholder">
                <i class="fas fa-cloud-upload-alt"></i>
                <text>点击上传图片（最多5张）</text>
              </view>
            </view>
            <!-- #endif -->
            <!-- #ifdef MP-WEIXIN || APP-PLUS -->
            <button class="gradient-btn1" @tap="chooseImages">选择图片（最多5张）</button>
            <!-- #endif -->
            <view class="image-preview-container">
              <view v-for="(image, index) in uploadedImages" :key="index" class="image-preview-item">
                <image :src="image" mode="aspectFill" />
                <view class="delete-btn" @click="removeImage(index)">×</view>
              </view>
            </view>
          </view>
        </view>

        <!-- 企业信息认证状态模块 -->
        <view class="company-info">
          <h2>企业信息</h2>
          
          <!-- 用户认证状态显示 -->
          <view class="auth-status-section">
            <view class="auth-status-item">
              <label>认证状态</label>
              <view class="auth-status-display" :class="{ 'authenticated': isUserAuthenticated, 'warning': !isUserAuthenticated }">
                {{ authStatusText }}
              </view>
              <button class="refresh-btn" @tap="refreshAuthStatus" title="刷新认证状态">
                <text class="refresh-icon">🔄</text>
              </button>
            </view>
            
            <!-- 简化的认证提示 -->
            <view v-if="!isUserAuthenticated && userAuth?.isLoggedIn" class="auth-warning">
              <text class="warning-text">⚠️ 需要完成企业认证才能发布任务</text>
              <button class="company-auth-btn" @tap="handleCompanyAuth">
                <text class="btn-icon">🏢</text>
                前往企业认证
              </button>
            </view>
          </view>
        </view>

        <view class="form-group map-form-group">
          <label>任务位置 (经纬度) <text class="required">*</text></label>
          <!-- #ifdef H5 -->
          <view class="map-container">
            <view id="map3D" class="map"></view>
            <view class="coordinates">
              <text>经度: {{ longitude }}</text>
              <text>纬度: {{ latitude }}</text>
            </view>
            <button class="locate-btn" @click="locateToCurrentPosition">定位到当前位置</button>
          </view>
          <!-- #endif -->
          <!-- #ifdef MP-WEIXIN || APP-PLUS -->
          <view class="map-container">
            <view class="map" style="height:220px">
              <map :latitude="Number(latitude) || 0" :longitude="Number(longitude) || 0" :scale="15" style="width:100%;height:100%">
                <!-- #ifdef APP-PLUS -->
                <cover-view class="map-wrapper"></cover-view>
                <!-- #endif -->
              </map>
            </view>
            <view class="coordinates">
              <text>经度: {{ longitude }}</text>
              <text>纬度: {{ latitude }}</text>
            </view>
            <button class="locate-btn" @tap="locateToCurrentPosition">定位到当前位置</button>
            <button class="locate-btn" style="margin-top:8px" @tap="chooseLocation">选择地图位置</button>
          </view>
          <!-- #endif -->
        </view>

        <view class="location-section">
          <view class="form-group location-group">
            <label>选择地区</label>
            <view class="location-select">
              <!-- #ifdef H5 -->
              <select v-model="selectedProvince" @change="handleProvinceChange" class="form-select">
                <option value="">选择省</option>
                <option v-for="province in provinces" :key="province.adcode" :value="province.adcode">
                  {{ province.name }}
                </option>
              </select>
              <!-- #endif -->
              <!-- #ifdef MP-WEIXIN || APP-PLUS -->
              <picker :range="provinceNames" :value="provinceIndex" @change="onProvincePickerChange" class="form-select">
                <view class="uni-input">{{ provinceNames[provinceIndex] || '选择省' }}</view>
              </picker>
              <!-- #endif -->

              <!-- #ifdef H5 -->
              <select v-model="selectedCity" @change="handleCityChange" :disabled="!selectedProvince" class="form-select">
                <option value="">选择市</option>
                <option v-for="city in cities" :key="city.adcode" :value="city.adcode">
                  {{ city.name }}
                </option>
              </select>
              <!-- #endif -->
              <!-- #ifdef MP-WEIXIN || APP-PLUS -->
              <picker :range="cityNames" :value="cityIndex" @change="onCityPickerChange" :disabled="!selectedProvince" class="form-select">
                <view class="uni-input">{{ cityNames[cityIndex] || '选择市' }}</view>
              </picker>
              <!-- #endif -->

              <!-- #ifdef H5 -->
              <select v-model="selectedDistrict" @change="handleDistrictChange" :disabled="!selectedCity" class="form-select">
                <option value="">选择县/区</option>
                <option v-for="district in districts" :key="district.adcode" :value="district.adcode">
                  {{ district.name }}
                </option>
              </select>
              <!-- #endif -->
              <!-- #ifdef MP-WEIXIN || APP-PLUS -->
              <picker :range="districtNames" :value="districtIndex" @change="onDistrictPickerChange" :disabled="!selectedCity" class="form-select">
                <view class="uni-input">{{ districtNames[districtIndex] || '选择县/区' }}</view>
              </picker>
              <!-- #endif -->
            </view>
          </view>

          <view class="form-group address-group">
            <label>线下见面地址 <text class="required">*</text></label>
            <input
              type="text"
              v-model="meetingAddress"
              @input="handleAddressInput"
              placeholder="请输入线下见面地址"
              required
              class="form-input"
            />
            <view v-if="suggestions.length" class="autocomplete-suggestions">
              <view
                v-for="(suggestion, index) in suggestions"
                :key="index"
                class="autocomplete-suggestions-item"
                @tap="selectSuggestion(suggestion)"
              >
                {{ suggestion.name }} - {{ suggestion.distance.text }}
              </view>
            </view>
          </view>

          <view class="form-group">
            <label>联系方式(电话/邮箱/微信)</label>
            <input type="tel" v-model="contactPhone" class="form-input" />
          </view>
        </view>

        <view class="ai-analysis-section">
          <button class="gradient-btn1" @click="handleAIAnalysis" :disabled="isAnalyzing">
            <span class="btn-icon" v-if="!isAnalyzing">🤖</span>
            <span class="spinner" v-else></span>
            {{ isAnalyzing ? '分析中...' : 'AI 智能分析' }}
          </button>
          
          <!-- 分析结果 -->
          <view v-if="aiAnalysisResults" class="ai-analysis-window">
            <h3>AI 分析结果</h3>
            <view v-html="aiAnalysisResults"></view>
          </view>
          <view v-if="aiAnalysisResults" class="analysis-results">
            <view class="result-item">
              <label>最低限价</label>
              <input type="text" :value="minPrice" disabled class="form-input disabled-input" />
            </view>
            <view class="result-item">
              <label>实际发布价格</label>
              <input type="number" v-model="actualPrice" @input="validateActualPrice" required class="form-input" />
              <span v-if="priceError" class="error-message">实际发布价格必须大于最低限价（{{ minPrice }}元）</span>
            </view>
          </view>
        </view>

        <!-- 悬浮分析进度弹窗 -->
        <view class="floating-analysis-modal" v-if="isAnalyzing">
          <view class="analysis-modal-content">
            <view class="analysis-modal-header">
              <h3>AI 智能分析中</h3>
              <view class="analysis-stage">{{ analysisStage }}</view>
            </view>
            
            <view class="analysis-modal-body">
              <view class="analysis-progress-circle">
                <view class="progress-circle" :style="{ '--progress': analysisProgress + '%' }">
                  <text class="progress-text">{{ Math.round(analysisProgress) }}%</text>
                </view>
              </view>
              
              <view class="analysis-progress-info">
                <view class="analysis-countdown">剩余 {{ analysisCountdown }} 秒</view>
              </view>
            </view>
          </view>
        </view>

        <!-- 发布按钮区域 -->
        <view class="publish-section">
          <button 
            class="gradient-btn publish-btn" 
            @click="handlePublishClick"
            @mousedown="handleMouseDown"
            @touchstart="handleTouchStart"
            :disabled="!isUserAuthenticated"
            :class="{ 'disabled': !isUserAuthenticated }"
          >
            {{ getPublishButtonText() }}
          </button>
          <view class="debug-info" style="font-size:12px;color:#999;margin-top:8px;">
            调试: isUserAuthenticated={{ isUserAuthenticated }}, isEditMode={{ isEditMode }}
          </view>
          
          <view v-if="!isUserAuthenticated" class="login-reminder">
            <text>{{ getLoginReminderText() }}</text>
          </view>
        </view>
      </view>
    </view>

    <!-- 悬浮进度条 -->
    <view v-if="publishInProgress" class="floating-progress">
      <view class="progress-header">
        <h3>任务发布进度</h3>
        <view class="progress-status">
          <view class="status-indicator"></view>
          {{ currentProgressStage }}
        </view>
        <button class="close-btn" @click="toggleProgressDetail">
          <i class="fas" :class="progressDetailVisible ? 'fa-chevron-down' : 'fa-chevron-up'"></i>
        </button>
      </view>
      <view class="progress-bar-container">
        <view class="progress-bar" :style="{ width: progressPercentage + '%' }"></view>
      </view>
      <view v-if="progressDetailVisible" class="progress-details" ref="progressContainerRef">
        <view v-for="(item, index) in progressHistory" :key="index" class="progress-item" 
             :class="{ 'active': item.active, 'completed': item.completed, 'latest': index === progressHistory.length - 1 }">
          <view class="progress-icon">
            <i :class="getProgressIcon(item)"></i>
          </view>
          <view class="progress-content">
            <view class="progress-message">{{ item.message }}</view>
            <view class="progress-time">{{ formatProgressTime(item.timestamp) }}</view>
          </view>
          <view v-if="index === progressHistory.length - 1" class="latest-badge">最新</view>
        </view>
      </view>
    </view>
  </view>
</template>

<script setup>
import { NETWORK_CONFIG } from '@/config/network.js'
import { ref, reactive, onMounted, onBeforeUnmount, nextTick, computed, watch } from "vue";
import { useUserStore } from '@/store/user';
import BackButton from '@/components/BackButton.vue'

const userStore = useUserStore();

// 编辑模式相关
const isEditMode = ref(false);
const editTaskId = ref(null);

// 表单数据 - 原始内容（用户输入的）
const originalTaskName = ref("");
const originalTaskRequirements = ref("");

// 表单数据 - 优化后的内容（用于发布）
const taskName = ref("");
const taskRequirements = ref("");
const isContentOptimized = ref(false); // 是否已优化
const isOptimizing = ref(false); // 是否正在优化
const taskDeadline = ref("");
const longitude = ref(""); // 经度
const latitude = ref(""); // 纬度
const meetingAddress = ref("");
const suggestions = ref([]); // 自动补全建议列表
const uploadedImages = ref([]);
const estimatedPriceRange = ref("");
const minPrice = ref("");
const actualPrice = ref("");
const contactPhone = ref("");

// AI 分析结果
const aiAnalysisResults = ref(null);
const priceError = ref(false);

// AI分析状态
const isAnalyzing = ref(false);
const analysisCountdown = ref(16);
const analysisStage = ref("");
const analysisProgress = ref(0);

// 最小日期（今天）
const minDate = ref(new Date().toISOString().split("T")[0]);

// 图片上传逻辑
const maxImages = 5;
const imageInput = ref(null);
// 初始化高德地图
const provinces = ref([]); // 省列表
const cities = ref([]); // 市列表
const districts = ref([]); // 县/区列表

const selectedProvince = ref(""); // 当前选中的省
const selectedCity = ref(""); // 当前选中的市
const selectedDistrict = ref(""); // 当前选中的县/区

// 平台检测
const systemInfo = uni.getSystemInfoSync();
const isH5 = false; // 只保留小程序端

// H5 相关变量
let map3D = null; // 声明全局变量
let marker3D = null; // 用于存储 3D 地图的动态标记
let geocoder = null; // 高德地图地理编码实例

// 小程序相关变量
const provinceNames = ref([]);
const cityNames = ref([]);
const districtNames = ref([]);
const provinceIndex = ref(0);
const cityIndex = ref(0);
const districtIndex = ref(0);

// 用户认证状态管理
const userAuth = ref({
isLoggedIn: false,
userId: null,
token: null,
companyVerified: false,
companyStatus: 'none'
});

// WebSocket 连接状态管理
const wsConnected = ref(false);
const wsRetryCount = ref(0);
const maxRetries = 3;
let wsConnection = null;

// 检查用户认证状态
const checkUserAuth = () => {
try {
  const token = uni.getStorageSync("accessToken");
  const profile = uni.getStorageSync("userProfile");
  const companyAuth = uni.getStorageSync("companyAuthStatus");
  
  console.log("检查认证状态:", { hasToken: !!token, hasProfile: !!profile, companyAuth });
  
  // 优先从userStore获取用户信息
  let userProfile = profile;
  if (!userProfile && userStore.profile) {
    userProfile = userStore.profile;
    console.log("从userStore获取用户信息:", userProfile);
  }
  
  if (token && userProfile) {
    // 优先使用creditCode判断企业认证状态
    console.log("检查creditCode:", {
      creditCode: userProfile.creditCode,
      type: typeof userProfile.creditCode,
      length: userProfile.creditCode?.length,
      isEmpty: !userProfile.creditCode,
      isEmptyString: userProfile.creditCode === '',
      trimResult: userProfile.creditCode?.trim(),
      trimEmpty: userProfile.creditCode?.trim() === ''
    });
    
    const hasCreditCode = userProfile.creditCode && userProfile.creditCode.trim() !== '';
    console.log("hasCreditCode 判断结果:", hasCreditCode);
    
    if (hasCreditCode) {
      userAuth.value = {
        isLoggedIn: true,
        userId: userProfile.id || userProfile.userId,
        token: token,
        companyVerified: true,
        companyStatus: 'approved'
      };
      console.log("用户已登录且企业已认证（通过creditCode判断）");
      return true;
    } else if (companyAuth && companyAuth.status === 'approved') {
      // 备用方案：使用companyAuthStatus
      userAuth.value = {
        isLoggedIn: true,
        userId: userProfile.id || userProfile.userId,
        token: token,
        companyVerified: true,
        companyStatus: 'approved'
      };
      console.log("用户已登录且企业已认证（通过companyAuthStatus判断）");
      return true;
    } else {
      // 没有企业认证或认证未通过
      userAuth.value = {
        isLoggedIn: true,
        userId: userProfile.id || userProfile.userId,
        token: token,
        companyVerified: false,
        companyStatus: companyAuth?.status || 'none'
      };
      console.log("用户已登录但需要企业认证");
      return false;
    }
  } else if (token) {
    // 有token但没有profile，尝试从userStore获取
    if (userStore.profile) {
      console.log("从userStore获取用户信息进行认证检查");
      return checkUserAuth(); // 递归调用，使用userStore中的profile
    } else {
      console.log("用户已登录但信息不完整，需要获取用户信息");
      userAuth.value = {
        isLoggedIn: true,
        userId: null,
        token: token,
        companyVerified: false,
        companyStatus: 'none'
      };
      return false;
    }
  } else {
    userAuth.value = {
      isLoggedIn: false,
      userId: null,
      token: null,
      companyVerified: false
    };
    return false;
  }
} catch (error) {
  console.error("检查用户认证状态失败:", error);
  userAuth.value = {
    isLoggedIn: false,
    userId: null,
    token: null,
    companyVerified: false
  };
  return false;
}
};

// WebSocket 连接管理
const connectWebSocket = () => {
try {
  const token = userAuth.value?.token || uni.getStorageSync("accessToken");
  if (!token) {
    console.log("无访问令牌，跳过 WebSocket 连接");
    return;
  }

  console.log("小程序环境，使用 uni.connectSocket");
  
  uni.connectSocket({
    url: `wss://${NETWORK_CONFIG.API_BASE_URL}/api/?accessToken=${token}`,
    success: () => {
      console.log("WebSocket 连接请求已发送");
      wsConnected.value = true;
    },
    fail: (error) => {
      console.error("WebSocket 连接失败:", error);
      handleWebSocketError(error);
    }
  });

  // 监听连接状态
  uni.onSocketOpen(() => {
    console.log("WebSocket 连接已打开");
    wsConnected.value = true;
    wsRetryCount.value = 0;
  });

  uni.onSocketError((error) => {
    console.error("WebSocket 发生错误:", error);
    wsConnected.value = false;
    handleWebSocketError(error);
  });

  uni.onSocketClose(() => {
    console.log("WebSocket 连接已关闭");
    wsConnected.value = false;
    handleReconnection();
  });

} catch (error) {
  console.error("WebSocket 连接初始化失败:", error);
}
};

const handleWebSocketError = (error) => {
if (wsRetryCount.value < maxRetries) {
  console.log(`WebSocket 连接失败，5 秒后进行第 ${wsRetryCount.value + 1} 次重试`);
  setTimeout(() => {
    wsRetryCount.value++;
    connectWebSocket();
  }, 5000);
} else {
  console.log("WebSocket 重试次数已达上限，停止重连");
  uni.showToast({
    title: "网络连接异常，部分功能可能受限",
    icon: 'none',
    duration: 3000
  });
}
};

const handleReconnection = () => {
if (wsRetryCount.value < maxRetries) {
  setTimeout(() => {
    wsRetryCount.value++;
    connectWebSocket();
  }, 5000);
}
};

// 处理 WebSocket 消息
const handleWebSocketMessage = (data) => {
console.log("收到 WebSocket 消息:", data);

// 根据消息类型处理不同的业务逻辑
if (data.type === 'task_progress') {
  handleTaskProgressUpdate(data);
} else if (data.type === 'notification') {
  // 处理通知消息
  uni.showToast({
    title: data.message || "收到新消息",
    icon: 'none'
  });
}
};

// 全局错误处理
const handleGlobalError = (error, context = '') => {
console.error(`${context} 错误:`, error);

let message = "操作失败，请稍后重试";
if (error.message) {
  message = error.message;
} else if (error.errMsg) {
  message = error.errMsg;
}

uni.showToast({
  title: message,
  icon: 'none',
  duration: 3000
});
};

// 基础分析辅助函数
const getTaskTypeFromContent = (content) => {
  if (!content) return "通用任务";
  
  const lowerContent = content.toLowerCase();
  
  if (lowerContent.includes("开发") || lowerContent.includes("编程") || lowerContent.includes("代码")) {
    return "开发任务";
  } else if (lowerContent.includes("设计") || lowerContent.includes("美工") || lowerContent.includes("ui")) {
    return "设计任务";
  } else if (lowerContent.includes("写作") || lowerContent.includes("文案") || lowerContent.includes("编辑")) {
    return "文案任务";
  } else if (lowerContent.includes("翻译") || lowerContent.includes("语言")) {
    return "翻译任务";
  } else if (lowerContent.includes("数据") || lowerContent.includes("分析") || lowerContent.includes("统计")) {
    return "数据分析任务";
  } else if (lowerContent.includes("测试") || lowerContent.includes("质量")) {
    return "测试任务";
  } else {
    return "通用任务";
  }
};

const getComplexityFromContent = (content) => {
  if (!content) return "中等";
  
  const lowerContent = content.toLowerCase();
  const wordCount = content.length;
  
  // 基于关键词判断复杂度
  const complexKeywords = ["复杂", "高级", "专业", "系统", "架构", "算法", "机器学习", "人工智能"];
  const simpleKeywords = ["简单", "基础", "入门", "快速", "简单"];
  
  const hasComplexKeywords = complexKeywords.some(keyword => lowerContent.includes(keyword));
  const hasSimpleKeywords = simpleKeywords.some(keyword => lowerContent.includes(keyword));
  
  if (hasComplexKeywords || wordCount > 200) {
    return "复杂";
  } else if (hasSimpleKeywords || wordCount < 50) {
    return "简单";
  } else {
    return "中等";
  }
};

const getPriceRangeFromContent = (content) => {
  const complexity = getComplexityFromContent(content);
  const taskType = getTaskTypeFromContent(content);
  
  // 基于任务类型和复杂度确定价格范围
  if (taskType === "开发任务") {
    switch (complexity) {
      case "简单": return "200-500元";
      case "中等": return "500-1500元";
      case "复杂": return "1500-5000元";
      default: return "500-1500元";
    }
  } else if (taskType === "设计任务") {
    switch (complexity) {
      case "简单": return "100-300元";
      case "中等": return "300-800元";
      case "复杂": return "800-2000元";
      default: return "300-800元";
    }
  } else if (taskType === "文案任务") {
    switch (complexity) {
      case "简单": return "50-200元";
      case "中等": return "200-500元";
      case "复杂": return "500-1200元";
      default: return "200-500元";
    }
  } else if (taskType === "翻译任务") {
    switch (complexity) {
      case "简单": return "100-300元";
      case "中等": return "300-600元";
      case "复杂": return "600-1500元";
      default: return "300-600元";
    }
  } else if (taskType === "数据分析任务") {
    switch (complexity) {
      case "简单": return "200-500元";
      case "中等": return "500-1200元";
      case "复杂": return "1200-3000元";
      default: return "500-1200元";
    }
  } else {
    // 通用任务
    switch (complexity) {
      case "简单": return "100-300元";
      case "中等": return "300-800元";
      case "复杂": return "800-2000元";
      default: return "300-800元";
    }
  }
};

// AI优化内容
const optimizeContent = async () => {
  if (!originalTaskName.value || !originalTaskRequirements.value) {
    uni.showToast({
      title: "请先填写原始标题和内容",
      icon: 'none',
      duration: 2000
    });
    return;
  }

  isOptimizing.value = true;
  
  try {
    const token = userAuth.value?.token || uni.getStorageSync("accessToken");
    
    if (!token) {
      uni.showToast({
        title: "请先登录",
        icon: 'none',
        duration: 2000
      });
      isOptimizing.value = false;
      return;
    }

    const response = await uni.request({
      url: `${NETWORK_CONFIG.API_BASE_URL}/task/optimize-content`,
      method: 'POST',
      header: {
        'Content-Type': 'application/json',
        'Access-Token': `Bearer ${token}`
      },
      data: {
        originalTitle: originalTaskName.value,
        originalDescription: originalTaskRequirements.value
      }
    });

    if (response.statusCode === 200 && response.data.success) {
      // 更新优化后的内容
      taskName.value = response.data.optimizedTitle;
      taskRequirements.value = response.data.optimizedDescription;
      isContentOptimized.value = true;
      
      uni.showToast({
        title: response.data.fromCache ? "已加载缓存内容" : "内容优化成功",
        icon: 'success',
        duration: 2000
      });
    } else {
      throw new Error(response.data?.message || "优化失败");
    }
  } catch (error) {
    console.error("优化内容失败:", error);
    uni.showToast({
      title: error.message || "优化失败，请重试",
      icon: 'none',
      duration: 3000
    });
  } finally {
    isOptimizing.value = false;
  }
};

// 当原始内容变化时，清除优化状态和缓存
const onOriginalContentChange = async () => {
  if (isContentOptimized.value) {
    // 清除优化状态
    isContentOptimized.value = false;
    taskName.value = "";
    taskRequirements.value = "";
    
    // 清除后端缓存
    try {
      const token = userAuth.value?.token || uni.getStorageSync("accessToken");
      if (token) {
        await uni.request({
          url: `${NETWORK_CONFIG.API_BASE_URL}/task/clear-optimization-cache`,
          method: 'POST',
          header: {
            'Access-Token': `Bearer ${token}`
          }
        });
        console.log("已清除优化缓存");
      }
    } catch (error) {
      console.error("清除缓存失败:", error);
      // 清除缓存失败不影响功能，继续执行
    }
  }
};

const handleAIAnalysis = async () => {
  try {
    // 获取任务的标题、内容和截止时间
    // 注意：AI分析用于报价，应该使用优化后的内容（如果已优化）
    // 因为优化后的内容更准确，报价会更合理
    // 如果还没有优化，则使用原始内容
    const title = isContentOptimized.value ? taskName.value : (originalTaskName.value || taskName.value);
    const content = isContentOptimized.value ? taskRequirements.value : (originalTaskRequirements.value || taskRequirements.value);
    const deadline = taskDeadline.value; // 截止时间
    
    // 如果没有优化，提示用户先优化内容
    if (!isContentOptimized.value) {
      uni.showToast({
        title: "建议先使用AI优化内容以获得更准确的报价",
        icon: 'none',
        duration: 3000
      });
    }

    if (!title || !content || !deadline || !latitude || !longitude) {
      uni.showToast({
        title: "请确保任务信息和经纬度完整！",
        icon: 'none'
      });
      return;
    }

    // 启动分析状态和倒计时
    isAnalyzing.value = true;
    analysisCountdown.value = 16;
    analysisStage.value = "地区分析中...";
    analysisProgress.value = 0;

    // 立即更新一次进度条，确保初始状态正确
    nextTick(() => {
      analysisProgress.value = 5; // 起始进度为5%
    });

    // 启动倒计时
    const countdownInterval = setInterval(() => {
      if (analysisCountdown.value > 0) {
        analysisCountdown.value--;
        // 更新进度条，确保进度平滑增长
        analysisProgress.value = 5 + ((16 - analysisCountdown.value) / 16) * 95;
        
        // 根据倒计时更新分析阶段
        if (analysisCountdown.value <= 16 && analysisCountdown.value > 10) {
          analysisStage.value = "地区分析中...";
        } else if (analysisCountdown.value <= 10 && analysisCountdown.value > 5) {
          analysisStage.value = "行情分析中...";
        } else if (analysisCountdown.value <= 5 && analysisCountdown.value > 0) {
          analysisStage.value = "报价计算中...";
        }
      } else {
        clearInterval(countdownInterval);
      }
    }, 1000);

    // 调用后端接口
    const result = await callAIAnalysis(latitude.value, longitude.value, title, content, deadline);
    
    // 如果在实际数据返回前倒计时未结束，清除倒计时
    clearInterval(countdownInterval);
    
    // 设置最终阶段和完成状态
    analysisStage.value = "生成报价中...";
    analysisProgress.value = 100;
    
    // 延迟一下，然后展示结果
    setTimeout(() => {
      aiAnalysisResults.value = result;
      isAnalyzing.value = false;
      
      // 成功提示
      uni.showToast({
        title: "AI分析完成！",
        icon: 'success',
        duration: 2000
      });
    }, 1000);
    
  } catch (error) {
    console.error("AI 分析过程失败:", error);
    
    // 清除倒计时
    if (countdownInterval) {
      clearInterval(countdownInterval);
    }
    
    // 重置分析状态
    isAnalyzing.value = false;
    analysisProgress.value = 0;
    analysisCountdown.value = 16;
    
    // 显示错误提示（callAIAnalysis 已经显示了具体错误）
    console.log("AI分析失败，错误详情:", error.message);
    
    // 如果 AI 分析失败，提供备用建议
    console.log("AI分析失败，提供备用建议，错误信息:", error.message);
    
    // 根据用户类型和错误类型提供不同的备用方案
    const isNetworkError = error.message.includes("网络") || error.message.includes("服务器") || error.message.includes("request:fail");
    const isAuthError = error.message.includes("认证") || error.message.includes("权限") || error.message.includes("401") || error.message.includes("403");
    
    if (isNetworkError || isAuthError) {
      // 网络或认证问题，提供离线建议
      let analysisResult = "";
      
      if (!userAuth.value?.companyVerified) {
        // 非企业用户的备用分析
        analysisResult = `
          <div style="color: #1890ff; padding: 16px; background: #f0f9ff; border-radius: 8px; margin: 16px 0;">
            <h4>🤖 AI分析结果（基础版）</h4>
            <p>基于任务描述的基础分析：</p>
            <div style="margin: 12px 0; padding: 12px; background: white; border-radius: 6px;">
              <p><strong>任务类型：</strong>${getTaskTypeFromContent(taskRequirements.value)}</p>
              <p><strong>复杂度评估：</strong>${getComplexityFromContent(taskRequirements.value)}</p>
              <p><strong>建议价格范围：</strong>${getPriceRangeFromContent(taskRequirements.value)}</p>
            </div>
            <p style="color: #666; font-size: 12px; margin-top: 12px;">
              💡 完成企业认证后可获得更精准的AI分析结果
            </p>
          </div>
        `;
      } else {
        // 企业用户的网络错误提示
        analysisResult = `
          <div style="color: #f56c6c; padding: 16px; background: #fef0f0; border-radius: 8px; margin: 16px 0;">
            <h4>⚠️ AI分析暂时不可用</h4>
            <p>由于网络或服务器问题，AI分析功能暂时不可用。建议您：</p>
            <ul style="margin: 8px 0; padding-left: 20px;">
              <li>检查网络连接</li>
              <li>稍后重试</li>
              <li>根据任务复杂度手动设置价格</li>
            </ul>
            <p style="margin-top: 12px; font-weight: bold;">参考价格范围：</p>
            <p>简单任务：50-200元</p>
            <p>中等任务：200-800元</p>
            <p>复杂任务：800-2000元</p>
          </div>
        `;
      }
      
      aiAnalysisResults.value = analysisResult;
      
      // 设置默认价格建议
      const priceRange = getPriceRangeFromContent(taskRequirements.value);
      const prices = priceRange.match(/(\d+)-(\d+)/);
      if (prices) {
        minPrice.value = prices[1];
        actualPrice.value = Math.round((parseInt(prices[1]) + parseInt(prices[2])) / 2).toString();
      } else {
        minPrice.value = "100";
        actualPrice.value = "300";
      }
    }
  }
};

const callAIAnalysis = async (latitude, longitude, title, content, deadline) => {
  try {
    // 可靠解析截止日期（避免字符串解析与时区导致的大量偏差）
    const parseYMDToLocalDate = (ymd) => {
      if (!ymd || typeof ymd !== 'string' || !/^[0-9]{4}-[0-9]{2}-[0-9]{2}$/.test(ymd)) {
        return null;
      }
      const [y, m, d] = ymd.split('-').map(Number);
      // 使用本地时区的年月日构造，设置到当天 23:59:59，避免当天选择被算为 0 小时
      return new Date(y, (m || 1) - 1, d || 1, 23, 59, 59, 0);
    };

    const currentTime = new Date();
    const deadlineTime = parseYMDToLocalDate(deadline);

    if (!deadlineTime || isNaN(deadlineTime.getTime())) {
      throw new Error('无效的截止日期');
    }

    const timeDifference = Math.max(0, (deadlineTime.getTime() - currentTime.getTime()) / (1000 * 60 * 60));
    const prompt = `
      任务标题：${title}
      任务内容：${content}
    `;

    console.log("开始 AI 分析，参数:", { latitude, longitude, title, content, deadline });
    console.log("分析提示:", prompt);
    console.log("用户认证状态:", { 
      isLoggedIn: userAuth.value?.isLoggedIn, 
      companyVerified: userAuth.value?.companyVerified,
      hasToken: !!userAuth.value?.token 
    });

    let result = "";
    analysisStage.value = "生成报价中...";

    // 使用阻塞式接口而不是流式接口，因为小程序不支持SSE
    console.log("小程序环境，使用阻塞式 AI 分析接口");
    
    try {
      // 改进token处理：优先使用userAuth中的token，如果没有则尝试从本地存储获取
      let token = userAuth.value?.token;
      if (!token) {
        token = uni.getStorageSync("accessToken");
        console.log("从本地存储获取token:", token ? "存在" : "不存在");
      }
      
      // 构建请求头
      const headers = {
        'Content-Type': 'text/plain'
      };
      
      // 只有在有token的情况下才添加Access-Token头
      if (token) {
        headers['Access-Token'] = `Bearer ${token}`;
        console.log("使用token进行AI分析请求");
      } else {
        console.log("无token，使用匿名请求进行AI分析");
      }

      const response = await uni.request({
        url: `${NETWORK_CONFIG.API_BASE_URL}/ai/blocking?latitude=${latitude}&longitude=${longitude}`,
        method: 'POST',
        data: prompt,
        header: headers
      });

      console.log("小程序 AI 分析响应:", response);

      // 小程序中 uni.request 的响应格式是 [error, response]
      let responseData = null;
      if (Array.isArray(response)) {
        // 小程序环境
        if (response[0]) {
          // 有错误
          console.error("请求错误:", response[0]);
          throw new Error(`请求失败: ${response[0].errMsg || '未知错误'}`);
        }
        responseData = response[1];
      } else {
        // 其他情况
        responseData = response;
      }

      console.log("响应数据:", responseData);

      // 改进状态码处理：支持更多成功状态码
      if (responseData && (responseData.statusCode === 200 || responseData.statusCode === 201)) {
        console.log("AI 分析响应数据结构:", responseData);
        console.log("responseData.data 类型:", typeof responseData.data);
        console.log("responseData.data 内容:", responseData.data);
        
        // 处理不同的响应数据格式
        if (typeof responseData.data === 'string') {
          result = responseData.data;
        } else if (typeof responseData.data === 'object' && responseData.data !== null) {
          // 检查是否是AI API的完整响应格式
          if (responseData.data.choices && responseData.data.choices[0] && responseData.data.choices[0].message) {
            // 这是AI API的完整响应格式，提取content
            result = responseData.data.choices[0].message.content;
            console.log("从AI API响应中提取内容:", result);
          } else if (responseData.data.message) {
            // 简单的消息格式
            result = responseData.data.message;
          } else if (responseData.data.content) {
            // 内容格式
            result = responseData.data.content;
          } else if (responseData.data.text) {
            // 文本格式
            result = responseData.data.text;
          } else if (responseData.data.result) {
            // 结果格式
            result = responseData.data.result;
          } else if (responseData.data.analysis) {
            // 分析格式
            result = responseData.data.analysis;
          } else if (responseData.data.response) {
            // 响应格式
            result = responseData.data.response;
          } else {
            // 其他对象格式，尝试提取有用信息
            console.log("尝试从对象中提取文本内容");
            const objStr = JSON.stringify(responseData.data);
            if (objStr.length > 10) {
              result = objStr;
            } else {
              result = "AI分析完成，但返回格式需要优化";
            }
          }
        } else {
          result = String(responseData.data || '');
        }
        
        console.log("处理后的 AI 分析结果:", result);
        
        // 解析AI分析结果中的价格信息
        // 支持多种格式：{10000},{50000},{30000} 或 10000,50000,30000
        console.log("开始解析价格，原始结果:", result);
        const priceMatch = result.match(/\{?(\d+)\}?,\{?(\d+)\}?,\{?(\d+)\}?/);
        if (priceMatch) {
          minPrice.value = parseInt(priceMatch[1], 10);
          actualPrice.value = parseInt(priceMatch[3], 10); // 使用中肯价（第三个价格）
          console.log("✅ 成功解析价格:", { 
            min: minPrice.value, 
            max: parseInt(priceMatch[2], 10), 
            actual: actualPrice.value 
          });
        } else {
          console.log("❌ 未能从结果中解析出价格格式，尝试其他格式");
          // 尝试其他可能的价格格式
          const alternativeMatch = result.match(/(\d+)\s*元.*?(\d+)\s*元.*?(\d+)\s*元/);
          if (alternativeMatch) {
            minPrice.value = parseInt(alternativeMatch[1], 10);
            actualPrice.value = parseInt(alternativeMatch[3], 10);
            console.log("✅ 使用备用格式解析出的价格:", { 
              min: minPrice.value, 
              actual: actualPrice.value 
            });
          } else {
            console.log("❌ 所有价格解析格式都失败");
            console.log("尝试解析的文本内容:", result.substring(0, 200) + "...");
            // 为非企业用户提供默认价格建议
            if (!userAuth.value?.companyVerified) {
              console.log("非企业用户，提供默认价格建议");
              minPrice.value = "100";
              actualPrice.value = "300";
            }
          }
        }
        
        aiAnalysisResults.value = result.replace(/\n/g, "<br>");
      } else {
        console.error("AI 分析响应状态码异常:", responseData?.statusCode);
        console.error("响应数据:", responseData);
        
        // 改进错误处理：提供更详细的错误信息
        let errorMsg = `AI分析失败: HTTP ${responseData?.statusCode || '未知状态码'}`;
        if (responseData?.data?.message) {
          errorMsg = responseData.data.message;
        } else if (responseData?.data?.error) {
          errorMsg = responseData.data.error;
        }
        
        throw new Error(errorMsg);
      }
    } catch (requestError) {
      console.error("小程序 AI 分析请求失败:", requestError);
      
      // 改进错误处理：区分不同类型的错误
      let errorMessage = "AI分析请求失败";
      if (requestError.message) {
        errorMessage = requestError.message;
      } else if (requestError.errMsg) {
        errorMessage = requestError.errMsg;
      }
      
      // 如果是网络错误，提供更友好的提示
      if (errorMessage.includes("request:fail") || errorMessage.includes("网络")) {
        errorMessage = "网络连接失败，请检查网络设置";
      }
      
      throw new Error(errorMessage);
    }

    if (!result || result.trim() === '') {
      throw new Error("AI 分析返回结果为空");
    }

    console.log("AI 分析完成，最终结果:", result);
    return result;
    
  } catch (error) {
    console.error("AI分析接口调用失败:", error);
    
    // 提供更友好的错误信息
    let userMessage = "AI分析失败，请稍后重试";
    if (error.message.includes("HTTP")) {
      userMessage = "网络请求失败，请检查网络连接";
    } else if (error.message.includes("响应流")) {
      userMessage = "服务器响应异常，请稍后重试";
    } else if (error.message.includes("无数据") || error.message.includes("结果为空")) {
      userMessage = "AI分析结果为空，请重新尝试";
    } else if (error.message.includes("网络连接失败")) {
      userMessage = "网络连接失败，请检查网络设置";
    } else if (error.message.includes("request:fail")) {
      userMessage = "请求失败，请检查网络连接";
    }
    
    // 显示用户友好的错误提示
    uni.showToast({
      title: userMessage,
      icon: 'none',
      duration: 3000
    });
    
    throw error;
  }
};

watch([longitude, latitude], ([newLng, newLat]) => {
  if (newLng && newLat) {
    fetchRegionByCoordinates(newLng, newLat); // 根据经纬度更新省市县
  }
});

const fetchRegionByCoordinates = async (lng, lat) => {
  try {
    console.log("开始根据经纬度获取地区信息:", { lng, lat });
    
    const res = await uni.request({
      url: "https://restapi.amap.com/v3/geocode/regeo",
      method: "GET",
      data: {
        key: "c0a49cb6bc13d4aae0b552bcb3482eac", // 替换为你的高德地图 API 密钥
        location: `${lng},${lat}`, // 经纬度
        radius: 1000, // 搜索半径
        extensions: "base", // 返回基本信息
      },
      header: {
        'Access-Token': `Bearer ${userAuth.value?.token || ''}`,
      }
    });

    console.log("逆地理编码响应:", res.data);

    if (res.data && res.data.regeocode && res.data.regeocode.addressComponent) {
      const address = res.data.regeocode.addressComponent;

      // 获取省、市、县的名称和 adcode
      const provinceName = address.province || "";
      const cityName = address.city || provinceName; // 有些直辖市没有 city 字段
      const districtName = address.district || "";
      const districtAdcode = address.adcode || "";

      console.log("解析出的地区信息:", { provinceName, cityName, districtName, districtAdcode });

      // 确保省列表已加载
      if (provinces.value.length === 0) {
        console.log("省列表为空，先加载省列表");
        await fetchProvinces();
      }

      // 更新省市县选择框
      const province = provinces.value.find((item) => item.name === provinceName);
      if (province) {
        selectedProvince.value = province.adcode;
        console.log("找到匹配的省份:", province);
        
        // 更新小程序选择器的索引
        provinceIndex.value = provinces.value.findIndex(p => p.adcode === province.adcode);
        
        // 加载市列表
        await fetchCities(selectedProvince.value);
        
        if (cities.value.length > 0) {
          const city = cities.value.find((item) => item.name === cityName);
          if (city) {
            selectedCity.value = city.adcode;
            console.log("找到匹配的城市:", city);
            
            // 更新小程序选择器的索引
            cityIndex.value = cities.value.findIndex(c => c.adcode === city.adcode);
            
            // 加载县/区列表
            await fetchDistricts(selectedCity.value);
            
            if (districts.value.length > 0) {
              const district = districts.value.find((item) => item.name === districtName);
              if (district) {
                selectedDistrict.value = district.adcode;
                console.log("找到匹配的区县:", district);
                
                // 更新小程序选择器的索引
                districtIndex.value = districts.value.findIndex(d => d.adcode === district.adcode);
              } else {
                // 如果找不到匹配的区县，使用adcode
                selectedDistrict.value = districtAdcode;
                console.log("使用adcode作为区县:", districtAdcode);
              }
            }
          } else {
            console.log("未找到匹配的城市:", cityName);
          }
        }
      } else {
        console.log("未找到匹配的省份:", provinceName);
      }
    } else {
      console.error("逆地理编码解析失败:", res.data);
    }
  } catch (error) {
    console.error("获取省市县信息失败:", error);
    handleGlobalError(error, "获取省市县信息");
  }
};

const fetchProvinces = async () => {
  try {
    const res = await uni.request({
      url: "https://restapi.amap.com/v3/config/district",
      method: "GET",
      data: {
        key: "c0a49cb6bc13d4aae0b552bcb3482eac", // 替换为你的高德地图 API 密钥
        keywords: "",
        subdistrict: 1,
        level: "country", // 获取国家级别的行政区划
      },
      header: {
        'Access-Token': `Bearer ${userAuth.value?.token || ''}`,
      }
    });

    console.log("省列表数据：", res.data); // 打印返回的数据

    // 确保数据格式正确
    if (res.data && res.data.districts && res.data.districts[1]?.districts) {
      provinces.value = res.data.districts[1].districts; // 提取省级数据
    } else if (res.data.districts[0]?.districts) {
      provinces.value = res.data.districts[0].districts; // 备用解析
    } else {
      console.error("省级数据解析失败:", res.data);
    }
  } catch (error) {
    handleGlobalError(error, "获取省列表");
  }
};

const fetchCities = async (provinceAdcode) => {
  try {
    const res = await uni.request({
      url: "https://restapi.amap.com/v3/config/district",
      method: "GET",
      data: {
        key: "c0a49cb6bc13d4aae0b552bcb3482eac",
        keywords: provinceAdcode,
        subdistrict: 1,
        level: "province",
      },
      header: {
        'Access-Token': `Bearer ${userAuth.value?.token || ''}`,
      }
    });

    if (res.data && res.data.districts && res.data.districts[0].districts) {
      cities.value = res.data.districts[0].districts; // 提取市级数据

      // 如果 selectedCity 已经有值，确保它在新的 cities 数据中
      if (!cities.value.some((city) => city.name === selectedCity.value)) {
        selectedCity.value = ""; // 如果不匹配，清空
      }
    } else {
      console.error("市级数据解析失败:", res.data);
    }
  } catch (error) {
    handleGlobalError(error, "获取市列表");
  }
};

const fetchDistricts = async (cityAdcode) => {
  try {
    const res = await uni.request({
      url: "https://restapi.amap.com/v3/config/district",
      method: "GET",
      data: {
        key: "c0a49cb6bc13d4aae0b552bcb3482eac",
        keywords: cityAdcode,
        subdistrict: 1,
        level: "city",
      },
      header: {
        'Access-Token': `Bearer ${userAuth.value?.token || ''}`,
      }
    });

    if (res.data && res.data.districts && res.data.districts[0].districts) {
      districts.value = res.data.districts[0].districts; // 提取县/区数据

      // 如果 selectedDistrict 已经有值，确保它在新的 districts 数据中
      if (!districts.value.some((district) => district.name === selectedDistrict.value)) {
        selectedDistrict.value = ""; // 如果不匹配，清空
      }
    } else {
      console.error("县/区数据解析失败:", res.data);
    }
  } catch (error) {
    handleGlobalError(error, "获取县/区列表");
  }
};

// 处理省选择
const handleProvinceChange = () => {
  if (selectedProvince.value) {
    fetchCities(selectedProvince.value); // 获取市列表
    selectedCity.value = "";
    selectedDistrict.value = "";
    cities.value = [];
    districts.value = [];
  }
};

// 处理市选择
const handleCityChange = () => {
  if (selectedCity.value) {
    fetchDistricts(selectedCity.value); // 获取县/区列表
    selectedDistrict.value = "";
    districts.value = [];
  }
};

// 处理县/区选择
const handleDistrictChange = async () => {
  if (selectedDistrict.value) {
    try {
      const res = await uni.request({
        url: "https://restapi.amap.com/v3/config/district",
        method: "GET",
        data: {
          key: "c0a49cb6bc13d4aae0b552bcb3482eac",
          keywords: selectedDistrict.value,
          subdistrict: 0,
        },
        header: {
          'Access-Token': `Bearer ${userAuth.value?.token || ''}`,
        }
      });

      const location = res.data.districts[0].center.split(",");
      const lng = parseFloat(location[0]);
      const lat = parseFloat(location[1]);

      longitude.value = lng;
      latitude.value = lat;

      // 小程序端不需要设置地图中心
      console.log("已更新经纬度:", { lng, lat });
    } catch (error) {
      handleGlobalError(error, "获取县/区中心点");
    }
  }
};

const handleAddressInput = async () => {
  if (!meetingAddress.value) {
    suggestions.value = [];
    return;
  }

  try {
    const res = await uni.request({
      url: "https://restapi.amap.com/v3/assistant/inputtips",
      method: "GET",
      data: {
        key: "c0a49cb6bc13d4aae0b552bcb3482eac",
        keywords: meetingAddress.value,
        location: `${longitude.value},${latitude.value}`,
        city: "",
        radius: 5000,
        datatype: 'all'
      },
      header: {
        'Access-Token': `Bearer ${userAuth.value?.token || ''}`,
      }
    });

    if (res.data && res.data.tips) {
      // 过滤掉没有位置信息的提示
      const validTips = res.data.tips.filter((tip) => tip.location);

      // 计算每个提示与当前位置的距离，并格式化距离
      const tipsWithDistance = validTips.map((tip) => {
        let dist = 0;
        
        // 检查tip.location是否存在且为字符串
        if (tip.location && typeof tip.location === 'string') {
          try {
            const [lng, lat] = tip.location.split(",").map(Number);
            
            // 小程序端使用简化距离计算
            const rad = (d) => (d * Math.PI) / 180;
            const R = 6378137;
            const dLat = rad(lat - Number(latitude.value));
            const dLng = rad(lng - Number(longitude.value));
            const a = Math.sin(dLat / 2) ** 2 + Math.cos(rad(Number(latitude.value))) * Math.cos(rad(lat)) * Math.sin(dLng / 2) ** 2;
            dist = 2 * R * Math.asin(Math.sqrt(a));
          } catch (error) {
            console.error("计算距离时出错:", error, "tip.location:", tip.location);
            dist = 0; // 如果计算出错，距离设为0
          }
        } else {
          console.warn("tip.location 不是有效的字符串:", tip.location);
          dist = 0;
        }
        
        return { ...tip, distance: formatDistance(dist) };
      });

      // 按距离从近到远排序
      suggestions.value = tipsWithDistance.sort((a, b) => (a.distance?.value || 0) - (b.distance?.value || 0));
    } else {
      suggestions.value = [];
    }
  } catch (error) {
    handleGlobalError(error, "获取地址输入提示");
    suggestions.value = [];
  }
};
const calculateDistance = (lng1, lat1, lng2, lat2) => {
  return AMap.GeometryUtil.distance([lng1, lat1], [lng2, lat2]);
};
const formatDistance = (distance) => {
  if (distance >= 1000) {
    return {
      text: `${(distance / 1000).toFixed(2)} km`, // 转换为公里并保留两位小数
      value: distance, // 原始距离值，用于排序
    };
  } else {
    return {
      text: `${distance.toFixed(0)} m`, // 显示为米
      value: distance, // 原始距离值，用于排序
    };
  }
};
const selectSuggestion = (suggestion) => {
  meetingAddress.value = suggestion.name; // 设置选中的地址
  suggestions.value = []; // 清空建议列表

  if (suggestion.location) {
    const [lng, lat] = suggestion.location.split(",").map(Number);
    longitude.value = lng;
    latitude.value = lat;

    // 小程序端不需要设置地图中心
    console.log("已选择地址，更新经纬度:", { lng, lat });
  }
};
const locateToCurrentPosition = () => {
  // 小程序端使用 uni.getLocation
  uni.getLocation({
    type: 'gcj02',
    success: (res) => {
      latitude.value = res.latitude;
      longitude.value = res.longitude;
      console.log("定位成功，当前位置:", { lat: res.latitude, lng: res.longitude });
    },
    fail: (err) => {
      console.error('小程序定位失败', err);
      uni.showToast({
        title: '定位失败',
        icon: 'none'
      });
    }
  });
};

const handleAddressSelect = () => {
  // 小程序端不需要使用地理编码器
  console.log("小程序环境，跳过地理编码处理");
};

const initMap = () => {
  // 小程序端不需要初始化 H5 地图
  console.log("小程序环境，跳过 H5 地图初始化");
};

const triggerImageUpload = () => {
  // 小程序端不需要触发文件选择
  console.log("小程序环境，使用 chooseImages 函数");
};

const handleImageUpload = (event) => {
  // 小程序端不需要处理文件上传事件
  console.log("小程序环境，跳过文件上传事件处理");
};

const handleDrop = (event) => {
  // 小程序端不需要处理拖拽事件
  console.log("小程序环境，跳过拖拽事件处理");
};

const processImageFiles = (files) => {
  // 小程序端不需要处理文件处理
  console.log("小程序环境，跳过文件处理");
};

const removeImage = (index) => {
  uploadedImages.value.splice(index, 1);
};

const chooseImages = () => {
  const remain = Math.max(0, maxImages - uploadedImages.value.length);
  if (remain <= 0) {
    uni.showToast({
      title: `最多${maxImages}张`,
      icon: 'none'
    });
    return;
  }
  uni.chooseImage({
    count: remain,
    sizeType: ['original', 'compressed'],
    sourceType: ['album', 'camera'],
    success: (res) => {
      const paths = res.tempFilePaths || [];
      uploadedImages.value.push(...paths);
    }
  });
};

const chooseLocation = () => {
  uni.chooseLocation({
    success: (res) => {
      if (res && res.longitude && res.latitude) {
        longitude.value = res.longitude;
        latitude.value = res.latitude;
        if (res.name) meetingAddress.value = res.name;
      }
    },
    fail: () => {
      uni.showToast({
        title: '选择位置失败',
        icon: 'none'
      });
    }
  });
};

// 进度跟踪相关状态
const publishInProgress = ref(false);
const progressHistory = ref([]);
const currentProgressStage = ref("");
const progressPercentage = ref(0);
const progressDetailVisible = ref(true); // 控制详情是否可见
const progressContainerRef = ref(null); // 进度容器的引用

// 切换进度详情的显示/隐藏
const toggleProgressDetail = () => {
  progressDetailVisible.value = !progressDetailVisible.value;
  
  // 如果是展开详情，等DOM更新后滚动到最新进度
  if (progressDetailVisible.value) {
    scrollToLatestProgress();
  }
};

// 滚动到最新进度
const scrollToLatestProgress = () => {
  nextTick(() => {
    if (progressContainerRef.value && progressHistory.value.length > 0) {
      const container = progressContainerRef.value;
      container.scrollTop = container.scrollHeight;
    }
  });
};

// 处理任务进度消息
const handleTaskProgressUpdate = (event) => {
  const message = event.detail;
  console.log("任务发布进度更新:", message);
  
  // 显示进度跟踪UI
  publishInProgress.value = true;
  
  // 构建详细的进度信息
  let detailedMessage = message.message;
  let progressData = message.data || {};
  
  // 根据不同的阶段添加详细信息
  if (message.stage === 'first_classify_complete' && progressData.classification) {
    const classification = progressData.classification;
    detailedMessage += `\n📋 分类结果：${classification.primary} > ${classification.secondary} > ${classification.tertiary}`;
  } else if (message.stage === 'first_rating_complete' && progressData.rating) {
    const rating = progressData.rating;
    detailedMessage += `\n⭐ 评级结果：${rating.description} (等级 ${rating.level})`;
  } else if (message.stage === 'classify_complete' && progressData.classification) {
    const classification = progressData.classification;
    const badgeIndex = progressData.badgeIndex || 1;
    detailedMessage += `\n📋 第${badgeIndex}次分类：${classification.primary} > ${classification.secondary} > ${classification.tertiary}`;
  } else if (message.stage === 'rating_complete' && progressData.rating) {
    const rating = progressData.rating;
    const badgeIndex = progressData.badgeIndex || 1;
    detailedMessage += `\n⭐ 第${badgeIndex}次评级：${rating.description} (等级 ${rating.level})`;
  } else if (message.stage === 'badge_created' && progressData.badge) {
    const badge = progressData.badge;
    const badgeIndex = progressData.badgeIndex || 1;
    detailedMessage += `\n🏆 第${badgeIndex}个铭牌生成完成：${badge.description} (等级 ${badge.level})`;
  } else if (message.stage === 'final_complete' && progressData.totalBadges) {
    detailedMessage += `\n🎉 共生成 ${progressData.totalBadges} 个铭牌，任务发布成功！`;
  }
  
  // 更新当前阶段
  currentProgressStage.value = detailedMessage;
  
  // 添加到进度历史
  const progressItem = {
    stage: message.stage,
    message: detailedMessage,
    timestamp: message.timestamp,
    data: progressData,
    active: true,
    completed: false
  };
  
  // 将之前的活动项标记为已完成
  progressHistory.value.forEach(item => {
    item.active = false;
    item.completed = true;
  });
  
  progressHistory.value.push(progressItem);
  
  // 更新进度百分比
  updateProgressPercentage(message.stage);
  
  // 滚动到最新进度
  scrollToLatestProgress();
  
  // 如果是最终完成，设置延迟后关闭进度显示
  if (message.stage === "final_complete") {
    setTimeout(() => {
      publishInProgress.value = false;
      // 成功通知
      uni.showToast({
        title: "任务发布成功！",
        icon: 'success'
      });
      // 根据平台跳转
      const systemInfo = uni.getSystemInfoSync();
      if (systemInfo.platform === 'web') {
        window.location.href = "/";
      } else {
        uni.switchTab({ url: "/pages/index/index" });
      }
    }, 3000);
  }
};

// 更新进度百分比
const updateProgressPercentage = (stage) => {
  const stages = {
    "start": 10,
    "classify_start": 15,
    "first_classify_complete": 25,
    "first_rating_start": 30,
    "first_rating_complete": 40,
    "additional_badges_start": 45,
    "classify_complete": 50,
    "rating_start": 55,
    "rating_complete": 60,
    "badge_created": 65,
    "publish_complete": 90,
    "final_complete": 100
  };
  
  progressPercentage.value = stages[stage] || progressPercentage.value;
};

// 获取进度图标
const getProgressIcon = (item) => {
  if (item.active) return "fas fa-spinner fa-spin";
  if (item.completed) return "fas fa-check-circle";
  return "fas fa-circle";
};

// 格式化进度时间
const formatProgressTime = (timestamp) => {
  if (!timestamp) return "";
  const date = new Date(timestamp);
  return date.toLocaleTimeString();
};

// 加载任务数据用于编辑
const loadTaskForEdit = async () => {
  try {
    const token = uni.getStorageSync('accessToken');
    const response = await uni.request({
      url: `${NETWORK_CONFIG.API_BASE_URL}/task/detail?taskId=${editTaskId.value}`,
      method: 'GET',
      header: { 'Access-Token': `Bearer ${token}` }
    });
    
    if (response.data && response.data.success) {
      const task = response.data.data;
      
      // 添加安全检查
      if (!task || !task.taskId) {
        throw new Error('任务数据格式错误');
      }
      
      // 编辑模式：将任务数据加载到优化后的字段
      // 注意：编辑模式下，假设任务已经是优化后的内容
      taskName.value = task.title || '';
      taskRequirements.value = task.description || '';
      // 原始内容设置为和优化后相同（编辑模式下）
      originalTaskName.value = task.title || '';
      originalTaskRequirements.value = task.description || '';
      isContentOptimized.value = true; // 编辑模式默认认为已优化
      
      taskDeadline.value = task.deadline || '';
      longitude.value = task.longitude || '';
      latitude.value = task.latitude || '';
      actualPrice.value = task.reward || 0;
      contactName.value = task.contactName || '';
      contactPhone.value = task.contactPhone || '';
      
      console.log('任务数据加载成功:', task);
    } else {
      throw new Error('加载任务数据失败: ' + (response.data?.message || '未知错误'));
    }
  } catch (error) {
    console.error('加载任务数据失败:', error);
    uni.showToast({ title: '加载任务数据失败', icon: 'none' });
  }
};

// 提交任务修改申请
const submitTaskModification = async () => {
  try {
    const token = uni.getStorageSync('accessToken');
    
    const modificationData = {
      taskId: editTaskId.value,
      title: taskName.value,
      description: taskRequirements.value,
      deadline: taskDeadline.value,
      longitude: longitude.value,
      latitude: latitude.value,
      reward: actualPrice.value,
      contactName: contactName.value,
      contactPhone: contactPhone.value
    };
    
    const response = await uni.request({
      url: `${NETWORK_CONFIG.API_BASE_URL}/task/submit-modification`,
      method: 'POST',
      data: modificationData,
      header: { 'Access-Token': `Bearer ${token}` }
    });
    
    if (response.data && response.data.success) {
      uni.showToast({ title: '修改申请已提交，等待挑战者投票', icon: 'success' });
      setTimeout(() => {
        uni.navigateBack();
      }, 1500);
    } else {
      uni.showToast({ title: response.data?.message || '提交失败', icon: 'none' });
    }
  } catch (error) {
    console.error('提交修改申请失败:', error);
    uni.showToast({ title: '提交失败，请重试', icon: 'none' });
  }
};

// 按钮事件处理函数
const handleMouseDown = () => {
  console.log('🖱️ 鼠标按下事件触发')
}

const handleTouchStart = () => {
  console.log('👆 触摸开始事件触发')
}

// 点击发布按钮的处理函数
const handlePublishClick = () => {
  console.log('========== 发布按钮被点击 ==========')
  console.log('isEditMode:', isEditMode.value)
  console.log('isUserAuthenticated:', isUserAuthenticated.value)
  console.log('isUserLoggedIn:', isUserLoggedIn.value)
  console.log('userAuth:', userAuth.value)
  console.log('按钮是否被禁用:', !isUserAuthenticated.value)
  
  if (!isUserAuthenticated.value) {
    console.log('⚠️ 按钮被禁用，用户未认证')
    return
  }
  
  if (isEditMode.value) {
    console.log('📝 编辑模式，调用 submitTaskModification')
    submitTaskModification()
  } else {
    console.log('📤 发布模式，调用 publishTask')
    publishTask()
  }
}

// 发布任务逻辑
const publishTask = async () => {
  console.log('开始发布任务...')
  console.log('用户认证状态:', userAuth.value)
  // 检查用户认证状态
  if (!userAuth.value?.isLoggedIn) {
    uni.showModal({
      title: "需要登录",
      content: "发布任务需要先完成登录，是否前往登录页面？",
      confirmText: "去登录",
      cancelText: "稍后",
      success: (res) => {
        if (res.confirm) {
          // 跳转到登录页面或用户页面
          uni.switchTab({ url: "/pages/user/index" });
        }
      }
    });
    return;
  }

  // 检查企业认证状态
  if (!userAuth.value?.companyVerified) {
    uni.showModal({
      title: "需要企业认证",
      content: "发布任务需要完成企业认证，是否立即前往认证？",
      confirmText: "去认证",
      cancelText: "稍后",
      success: (res) => {
        if (res.confirm) {
          handleCompanyAuth();
        }
      }
    });
    return;
  }

  if (!taskName.value || !taskRequirements.value || !taskDeadline.value || !meetingAddress.value) {
    uni.showToast({
      title: "请填写所有必填字段",
      icon: 'none'
    });
    return;
  }

  // 检查是否已经进行AI分析
  console.log('检查AI分析结果:')
  console.log('aiAnalysisResults.value:', aiAnalysisResults.value)
  console.log('minPrice.value:', minPrice.value, '类型:', typeof minPrice.value)
  console.log('actualPrice.value:', actualPrice.value, '类型:', typeof actualPrice.value)
  
  // 检查是否为null、undefined或空字符串（不能用!value因为0会被误判）
  const hasAiAnalysis = aiAnalysisResults.value !== null && aiAnalysisResults.value !== undefined && aiAnalysisResults.value !== ''
  const hasMinPrice = minPrice.value !== null && minPrice.value !== undefined && minPrice.value !== ''
  const hasActualPrice = actualPrice.value !== null && actualPrice.value !== undefined && actualPrice.value !== ''
  
  console.log('检查结果 - hasAiAnalysis:', hasAiAnalysis, 'hasMinPrice:', hasMinPrice, 'hasActualPrice:', hasActualPrice)
  
  if (!hasAiAnalysis || !hasMinPrice || !hasActualPrice) {
    console.log('❌ AI分析检查未通过')
    uni.showToast({
      title: "您还没有智能分析！请先点击AI智能分析",
      icon: 'none',
      duration: 3000
    });
    return;
  }
  
  console.log('✅ AI分析检查通过')

  // 验证价格
  const actualPriceNum = parseFloat(actualPrice.value) || 0;
  const minPriceNum = parseFloat(minPrice.value) || 0;
  if (actualPriceNum <= minPriceNum) {
    uni.showToast({
      title: `实际发布价格必须大于最低限价（${minPrice.value}元）`,
      icon: 'none',
      duration: 3000
    });
    return;
  }

  // 重置进度状态
  publishInProgress.value = true;
  progressHistory.value = [];
  currentProgressStage.value = "准备发布任务...";
  progressPercentage.value = 5;

  // 验证是否已优化
  if (!isContentOptimized.value) {
    uni.showToast({
      title: "请先使用AI优化内容",
      icon: 'none',
      duration: 3000
    });
    return;
  }

  // 验证优化后的内容不能为空
  if (!taskName.value || !taskRequirements.value) {
    uni.showToast({
      title: "优化后的标题和内容不能为空",
      icon: 'none',
      duration: 3000
    });
    return;
  }

  const taskData = {
    title: taskName.value, // 使用优化后的标题
    description: taskRequirements.value, // 使用优化后的描述
    reward: actualPrice.value,
    adCode: meetingAddress.value,
    deadline: taskDeadline.value,
    longitude: longitude.value,
    latitude: latitude.value,
    meetingAddress: meetingAddress.value,
    // 传递原始内容用于验证
    originalTitle: originalTaskName.value,
    originalDescription: originalTaskRequirements.value,
  };

  console.log('准备发送请求，任务数据:', taskData)
  console.log('请求URL:', `${NETWORK_CONFIG.API_BASE_URL}/task/publish`)

  try {
    const res = await uni.request({
      url: `${NETWORK_CONFIG.API_BASE_URL}/task/publish`,
      method: "POST",
      data: taskData,
      header: {
        "Content-Type": "application/json",
        'Access-Token': `Bearer ${userAuth.value?.token || ''}`,
      }
    })
    
    console.log('收到响应:', res)
    
    if (res.statusCode !== 200) {
      publishInProgress.value = false;
      throw new Error(res.data?.message || "发布失败");
    }

    // 任务已提交成功，显示提示信息
    uni.showToast({
      title: res.data?.message || "任务已提交，正在分类与评级中",
      icon: 'success',
      duration: 3000
    });

    // 更新进度状态
    currentProgressStage.value = "任务已提交，正在分类与评级中...";
    progressPercentage.value = 50;

    // 设置一个超时，如果30秒后还没收到完成消息，就提示并返回主页
    setTimeout(() => {
      if (progressPercentage.value < 100) {
        uni.showToast({
          title: "任务已提交，请查看消息中心获取最新状态",
          icon: 'none',
          duration: 3000
        });
        // 跳转到消息页面
        uni.switchTab({ url: "/pages/message/index" });
      }
    }, 30000);
    
  } catch (error) {
    console.error('发布任务失败:', error)
    console.error('错误详情:', error.message, error.stack)
    publishInProgress.value = false;
    handleGlobalError(error, "发布任务");
  }
};

const validateActualPrice = () => {
  const actualPriceNum = parseFloat(actualPrice.value) || 0;
  const minPriceNum = parseFloat(minPrice.value) || 0;
  
  // 实际价格必须大于最低限价（不能等于）
  if (actualPriceNum <= minPriceNum) {
    priceError.value = true; // 显示错误提示
  } else {
    priceError.value = false; // 隐藏错误提示
  }
};

// 调试认证状态
const debugAuthStatus = () => {
  const token = uni.getStorageSync("accessToken");
  const profile = uni.getStorageSync("userProfile");
  const companyAuth = uni.getStorageSync("companyAuthStatus");
  
  console.log("=== 认证状态调试信息 ===");
  console.log("本地存储 - accessToken:", token ? "存在" : "不存在");
  console.log("本地存储 - userProfile:", profile ? "存在" : "不存在");
  console.log("本地存储 - companyAuthStatus:", companyAuth);
  console.log("profile.creditCode:", profile?.creditCode);
  console.log("profile.creditCode 类型:", typeof profile?.creditCode);
  console.log("profile.creditCode 长度:", profile?.creditCode?.length);
  console.log("profile.creditCode 是否为空字符串:", profile?.creditCode === '');
  console.log("profile.creditCode 是否为空:", !profile?.creditCode);
  console.log("profile.creditCode trim后:", profile?.creditCode?.trim());
  console.log("当前 userAuth 状态:", userAuth.value);
  console.log("==========================");
};

onMounted(async () => {
  try {
    console.log("页面加载，开始初始化...");
    
  // 检查是否为编辑模式
  const pages = getCurrentPages();
  const currentPage = pages[pages.length - 1];
  const options = currentPage?.options || {};
  
  console.log("页面选项:", options);
  
  if (options.taskId && options.mode === 'edit') {
    isEditMode.value = true;
    editTaskId.value = options.taskId;
    console.log("进入编辑模式，任务ID:", editTaskId.value);
    await loadTaskForEdit();
  }
    
    // 首先尝试从userStore获取用户信息
    if (userStore.profile && userStore.profile.uid) {
      console.log("从userStore获取到用户信息:", userStore.profile);
      // 同步到本地存储
      uni.setStorageSync("userProfile", userStore.profile);
      
      // 立即检查认证状态（使用userStore的数据）
      checkUserAuth();
    } else {
      // 如果userStore没有数据，从localStorage获取
      const token = uni.getStorageSync("accessToken");
      const profile = uni.getStorageSync("userProfile");
      
      console.log("从localStorage获取用户信息:", { hasToken: !!token, hasProfile: !!profile });
      
      // 检查用户认证状态
      checkUserAuth();
    }
    
    // 调试认证状态
    debugAuthStatus();
    
    // 输出用户认证详细状态
    console.log('========== 页面加载完成后的用户状态 ==========')
    console.log('isUserLoggedIn:', isUserLoggedIn.value)
    console.log('isUserAuthenticated:', isUserAuthenticated.value)
    console.log('userAuth:', userAuth.value)
    console.log('isEditMode:', isEditMode.value)
    console.log('按钮文本:', getPublishButtonText())
    console.log('==========================================')
    
    // 如果用户已登录但没有完整信息，尝试自动登录
    if (userAuth.value?.isLoggedIn && !userAuth.value?.userId) {
      console.log("用户已登录但信息不完整，尝试自动登录");
      const autoLoginSuccess = await checkAndAutoLogin();
      
      if (autoLoginSuccess) {
        console.log("自动登录成功，用户信息已补充");
        // 检查企业认证状态
        await checkCompanyAuthStatus();
      } else {
        console.log("自动登录失败，但用户仍处于登录状态");
      }
    }
    
    // 获取省列表
    await fetchProvinces();
    
    // 设置最小日期为今天
    minDate.value = new Date().toISOString().split("T")[0];
    
    // 初始化地图
    initMap();
    
    // 设置认证状态监听器
    setupAuthListener();
    
    // 连接 WebSocket（只有在用户已认证且企业已认证时才连接）
    if (userAuth.value?.token && userAuth.value?.companyVerified) {
      connectWebSocket();
    }
    
    // 如果用户已登录但未企业认证，显示提示
    if (userAuth.value?.isLoggedIn && !userAuth.value?.companyVerified) {
      setTimeout(() => {
        uni.showModal({
          title: "需要企业认证",
          content: "检测到您尚未完成企业认证，发布任务需要完成认证，是否立即前往？",
          confirmText: "去认证",
          cancelText: "稍后",
          success: (res) => {
            if (res.confirm) {
              handleCompanyAuth();
            }
          }
        });
      }, 1000);
    }
    
    // 初始化完成后再次调试认证状态
    setTimeout(() => {
      console.log("=== 初始化完成后的认证状态 ===");
      debugAuthStatus();
    }, 1000);
    
  } catch (error) {
    console.error("页面初始化失败:", error);
    handleGlobalError(error, "页面初始化");
  }
});

// 页面显示时检查认证状态
const onShow = async () => {
  try {
    console.log("页面显示，检查认证状态");
    
    // 首先尝试从userStore获取用户信息
    if (userStore.profile && userStore.profile.uid) {
      console.log("页面显示时从userStore获取到用户信息:", userStore.profile);
      // 同步到本地存储
      uni.setStorageSync("userProfile", userStore.profile);
    }
    
    // 检查本地存储的认证状态
    checkUserAuth();
    
    // 如果用户已登录但没有完整信息，尝试自动登录
    if (userAuth.value?.isLoggedIn && !userAuth.value?.userId) {
      console.log("页面显示时用户信息不完整，尝试自动登录");
      const autoLoginSuccess = await checkAndAutoLogin();
      
      if (autoLoginSuccess) {
        console.log("页面显示时自动登录成功");
        // 检查企业认证状态
        await checkCompanyAuthStatus();
        // 如果自动登录成功，连接 WebSocket
        if (!wsConnected.value && userAuth.value?.companyVerified) {
          connectWebSocket();
        }
      }
    }
    
    // 每次显示页面时都检查企业认证状态（如果用户已登录）
    if (userAuth.value?.isLoggedIn && userAuth.value?.token) {
      await checkCompanyAuthStatus();
    }
    
  } catch (error) {
    console.error("页面显示时认证检查失败:", error);
  }
};

// 页面隐藏时清理
const onHide = () => {
  console.log("页面隐藏");
  // 可以在这里做一些清理工作
};

// 页面卸载时清理
const onUnload = () => {
  console.log("页面卸载，清理资源");
  if (wsConnection) {
    wsConnection.close();
  }
};

// 清理
onBeforeUnmount(() => {
  // 清理工作
  if (wsConnection) {
    wsConnection.close();
  }
});

// 小程序相关处理函数
const onProvincePickerChange = (e) => {
  provinceIndex.value = e.detail.value;
  if (provinces.value[provinceIndex.value]) {
    selectedProvince.value = provinces.value[provinceIndex.value].adcode;
    fetchCities(selectedProvince.value);
    selectedCity.value = "";
    selectedDistrict.value = "";
    cityIndex.value = 0;
    districtIndex.value = 0;
  }
};

const onCityPickerChange = (e) => {
  cityIndex.value = e.detail.value;
  if (cities.value[cityIndex.value]) {
    selectedCity.value = cities.value[cityIndex.value].adcode;
    fetchDistricts(selectedCity.value);
    selectedDistrict.value = "";
    districtIndex.value = 0;
  }
};

const onDistrictPickerChange = (e) => {
  districtIndex.value = e.detail.value;
  if (districts.value[districtIndex.value]) {
    selectedDistrict.value = districts.value[districtIndex.value].adcode;
    handleDistrictChange();
  }
};

// 日期选择器处理函数
const onDateChange = (e) => {
  taskDeadline.value = e.detail.value;
  console.log("选择的日期:", taskDeadline.value);
};

// 监听省市县数据变化，更新小程序选择器数据
watch(provinces, (newProvinces) => {
  provinceNames.value = newProvinces.map(p => p.name);
});

watch(cities, (newCities) => {
  cityNames.value = newCities.map(c => c.name);
});

watch(districts, (newDistricts) => {
  districtNames.value = newDistricts.map(d => d.name);
});

// 计算属性：检查用户是否已登录
const isUserLoggedIn = computed(() => {
  return userAuth.value?.isLoggedIn && userAuth.value?.token;
});

// 计算属性：检查用户是否完全认证（登录+企业认证）
const isUserAuthenticated = computed(() => {
  return isUserLoggedIn.value && userAuth.value?.companyVerified;
});

// 计算属性：显示认证状态信息
const authStatusText = computed(() => {
  if (!userAuth.value) {
    return "正在检查认证状态...";
  }
  
  if (userAuth.value.isLoggedIn && userAuth.value.companyVerified) {
    return `已认证 (用户ID: ${userAuth.value.userId || '未知'})`;
  } else if (userAuth.value.isLoggedIn && userAuth.value.token) {
    return "需要企业认证";
  } else if (userAuth.value.token) {
    return "Token 有效，但用户信息不完整";
  } else {
    return "未登录";
  }
});



// 手动获取用户信息（备用方案）
const fetchUserInfoManually = async () => {
  try {
    const token = uni.getStorageSync("accessToken");
    if (!token) {
      console.log("无token，无法获取用户信息");
      return false;
    }

    // 尝试其他可能的用户信息接口
    const response = await uni.request({
      url: "${NETWORK_CONFIG.API_BASE_URL}/user/info", // 尝试其他接口
      method: "GET",
      header: {
        'Access-Token': `Bearer ${token}`,
      }
    });

    console.log("手动获取用户信息响应:", response);

    let responseData = null;
    if (Array.isArray(response)) {
      if (response[0]) {
        console.error("请求失败:", response[0]);
        return false;
      }
      responseData = response[1];
    } else {
      responseData = response;
    }

    if (responseData && responseData.statusCode === 200) {
      const userProfile = responseData.data;
      uni.setStorageSync("userProfile", userProfile);
      
      // 更新认证状态
      userAuth.value = {
        isLoggedIn: true,
        userId: userProfile.id || userProfile.userId,
        token: token,
        companyVerified: false
      };
      
      console.log("手动获取用户信息成功:", userProfile);
      return true;
    }

    return false;
  } catch (error) {
    console.error("手动获取用户信息失败:", error);
    return false;
  }
};

// 检查登录状态并尝试自动登录
const checkAndAutoLogin = async () => {
  try {
    const token = uni.getStorageSync("accessToken");
    if (token) {
      // 有 token，尝试验证有效性
      const response = await uni.request({
        url: "${NETWORK_CONFIG.API_BASE_URL}/user/profile",
        method: "GET",
        header: {
          'Access-Token': `Bearer ${token}`,
        }
      });

      console.log("自动登录API响应:", response);

      // 处理不同平台的响应格式
      let responseData = null;
      if (Array.isArray(response)) {
        // 小程序环境
        if (response[0]) {
          console.error("请求失败:", response[0]);
          // 请求失败，但保留token，可能是网络问题
          return false;
        }
        responseData = response[1];
      } else {
        // 其他情况
        responseData = response;
      }

      if (responseData && responseData.statusCode === 200) {
        // token 有效，更新用户信息
        const userProfile = responseData.data;
        uni.setStorageSync("userProfile", userProfile);
        
        // 更新认证状态
        userAuth.value = {
          isLoggedIn: true,
          userId: userProfile.id || userProfile.userId,
          token: token
        };
        
        console.log("自动登录成功，用户信息:", userProfile);
        return true;
      } else if (responseData && responseData.statusCode === 404) {
        // API返回404，尝试备用方案
        console.log("用户信息接口返回404，尝试备用方案");
        return await fetchUserInfoManually();
      } else {
        // 其他错误状态码，可能是token过期
        console.log("token 可能已过期，清除存储");
        uni.removeStorageSync("accessToken");
        uni.removeStorageSync("userProfile");
        return false;
      }
    }
    return false;
  } catch (error) {
    console.error("自动登录检查失败:", error);
    // 网络错误等异常情况，保留token
    return false;
  }
};

// 监听用户认证状态变化
const setupAuthListener = () => {
  // 小程序环境使用定时检查
  setInterval(() => {
    if (!userAuth.value?.isLoggedIn) {
      checkAndAutoLogin();
    }
  }, 30000);
};

// 刷新用户认证状态
const refreshAuthStatus = async () => {
  try {
    console.log("手动刷新认证状态");
    const autoLoginSuccess = await checkAndAutoLogin();
    
    if (autoLoginSuccess) {
      // 如果认证成功，连接 WebSocket
      if (!wsConnected.value) {
        connectWebSocket();
      }
      
      uni.showToast({
        title: "认证状态已更新",
        icon: 'success',
        duration: 2000
      });
    } else {
      uni.showToast({
        title: "请先完成登录",
        icon: 'none',
        duration: 2000
      });
    }
  } catch (error) {
    console.error("刷新认证状态失败:", error);
    handleGlobalError(error, "刷新认证状态");
  }
};

// 处理企业认证
const handleCompanyAuth = () => {
  // 小程序环境直接跳转
  uni.navigateTo({
    url: "/pages/company/index",
    fail: (err) => {
      console.error("跳转企业认证页面失败:", err);
      // 如果跳转失败，尝试使用 switchTab
      uni.switchTab({
        url: "/pages/company/index",
        fail: (switchErr) => {
          console.error("跳转企业认证页面也失败:", switchErr);
          uni.showToast({
            title: "页面跳转失败，请手动前往企业认证页面",
            icon: 'none'
          });
        }
      });
    }
  });
};

// 检查企业认证状态
const checkCompanyAuthStatus = async () => {
  try {
    const token = userAuth.value?.token;
    if (!token) {
      console.log("无token，无法检查企业认证状态");
      return;
    }

    // 首先检查本地profile中的creditCode
    const profile = uni.getStorageSync("userProfile");
    if (profile && profile.creditCode && profile.creditCode.trim() !== '') {
      console.log("通过creditCode判断企业已认证:", profile.creditCode);
      userAuth.value.companyVerified = true;
      userAuth.value.companyStatus = 'approved';
      return;
    }

    // 如果creditCode不存在，则调用服务器接口检查
    const response = await uni.request({
      url: "${NETWORK_CONFIG.API_BASE_URL}/company/auth/status",
      method: "GET",
      header: {
        'Access-Token': `Bearer ${token}`,
      }
    });

    console.log("企业认证状态响应:", response);

    // 处理不同平台的响应格式
    let responseData = null;
    if (Array.isArray(response)) {
      // 小程序环境
      if (response[0]) {
        console.error("请求失败:", response[0]);
        return;
      }
      responseData = response[1];
    } else {
      // 其他情况
      responseData = response;
    }

    if (responseData && responseData.statusCode === 200) {
      const companyAuthData = responseData.data;
      console.log("企业认证状态:", companyAuthData);
      
      // 更新本地存储
      uni.setStorageSync("companyAuthStatus", companyAuthData);
      
      // 更新认证状态
      if (companyAuthData.status === 'approved') {
        userAuth.value.companyVerified = true;
        userAuth.value.companyStatus = 'approved';
      } else if (companyAuthData.status === 'pending') {
        userAuth.value.companyVerified = false;
        userAuth.value.companyStatus = 'pending';
      } else if (companyAuthData.status === 'rejected') {
        userAuth.value.companyVerified = false;
        userAuth.value.companyStatus = 'rejected';
      }
      
      console.log("企业认证状态已更新:", userAuth.value);
    }
  } catch (error) {
    console.error("检查企业认证状态失败:", error);
  }
};

// 获取企业认证按钮文本
const getCompanyAuthButtonText = () => {
  if (userAuth.value?.companyStatus === 'pending') {
    return '企业认证申请中';
  } else if (userAuth.value?.companyStatus === 'rejected') {
    return '重新认证';
  } else {
    return '企业认证';
  }
};

// 获取发布按钮文本
const getPublishButtonText = () => {
  if (isUserAuthenticated.value) {
    return isEditMode.value ? '申请修改' : '发布任务';
  } else if (isUserLoggedIn.value) {
    return '需要企业认证';
  } else {
    return '请先登录';
  }
};

// 获取登录提醒文本
const getLoginReminderText = () => {
  if (isUserLoggedIn.value) {
    return '发布任务前需要完成企业认证';
  } else {
    return '发布任务前需要先完成用户登录';
  }
};
</script>

<style scoped>
.publish-task-page {
  min-height: 100vh;
  background: #ffffff;
  font-family: 'PingFang SC', 'Microsoft YaHei', Arial, sans-serif;
  position: relative;
  overflow-x: hidden;
}

.background {
  position: fixed;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
  background: linear-gradient(135deg, #6366f1 0%, #8b5cf6 100%);
  opacity: 0.05;
  z-index: -1;
}

.bubbles {
  position: absolute;
  width: 100%;
  height: 100%;
  overflow: hidden;
}

.bubble {
  position: absolute;
  bottom: -20px;
  width: 40px;
  height: 40px;
  background: rgba(255, 255, 255, 0.1);
  border-radius: 50%;
  animation: bubble-rise 8s infinite;
}

.bubble:nth-child(1) {
  left: 10%;
  animation-delay: 0s;
}

.bubble:nth-child(2) {
  left: 50%;
  animation-delay: 3s;
}

.bubble:nth-child(3) {
  left: 80%;
  animation-delay: 6s;
}

.container {
  max-width: 100%;
  margin: 0;
  padding: 16px;
  box-sizing: border-box;
}

.navigation {
  margin-bottom: 20px;
}

.back-button {
  display: inline-flex;
  align-items: center;
  justify-content: center;
  padding: 12px 20px;
  background: #ffffff;
  border-radius: 12px;
  border: 1px solid #e2e8f0;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.05);
  cursor: pointer;
  transition: all 0.2s ease;
  text-decoration: none;
  min-height: 44px;
}

.back-button:hover {
  transform: scale(0.98);
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.1);
}

.back-text {
  color: #4a5568;
  font-size: 15px;
  font-weight: 500;
}

.publish-form {
  background: #ffffff;
  border-radius: 16px;
  padding: 20px;
  box-shadow: 0 4px 16px rgba(0, 0, 0, 0.05);
}

.publish-form .page-title {
  color: #4a5568;
  font-size: 20px;
  font-weight: bold;
  margin-bottom: 24px;
  text-align: center;
}

.form-group {
  margin-bottom: 16px;
}

.optimize-btn, .re-optimize-btn {
  width: 100%;
  padding: 12px 20px;
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
  color: white;
  border: none;
  border-radius: 8px;
  font-size: 16px;
  font-weight: 600;
  cursor: pointer;
  transition: all 0.3s ease;
  box-shadow: 0 4px 12px rgba(102, 126, 234, 0.3);
  margin-top: 8px;
}

.optimize-btn:hover, .re-optimize-btn:hover {
  transform: translateY(-2px);
  box-shadow: 0 6px 16px rgba(102, 126, 234, 0.4);
}

.optimize-btn:disabled, .re-optimize-btn:disabled {
  opacity: 0.6;
  cursor: not-allowed;
  transform: none;
}

.re-optimize-btn {
  background: linear-gradient(135deg, #f093fb 0%, #f5576c 100%);
  margin-top: 8px;
  width: auto;
  padding: 8px 16px;
  font-size: 14px;
}

.optimized-input {
  border: 2px solid #4caf50 !important;
  background-color: #f1f8f4 !important;
}

.hint-text {
  font-size: 12px;
  color: #666;
  margin-top: 4px;
  line-height: 1.4;
}

.form-group label {
  display: block;
  color: #4a5568;
  font-size: 15px;
  font-weight: 500;
  margin-bottom: 8px;
}

.required {
  color: #ff4d4f;
}

.form-input, .form-textarea, .form-select {
  width: 100%;
  min-height: 48px;
  padding: 12px 16px;
  border: 1px solid #e2e8f0;
  border-radius: 12px;
  font-size: 15px;
  color: #4a5568;
  background: #ffffff;
  transition: all 0.2s ease;
  box-sizing: border-box;
}

.form-input:focus, .form-textarea:focus, .form-select:focus {
  outline: none;
  border-color: #6366f1;
  box-shadow: 0 0 0 3px rgba(99, 102, 241, 0.1);
}

.form-picker {
  width: 100%;
  min-height: 48px;
  padding: 12px 16px;
  border: 1px solid #e2e8f0;
  border-radius: 12px;
  font-size: 15px;
  color: #4a5568;
  background: #ffffff;
  transition: all 0.2s ease;
  box-sizing: border-box;
  display: flex;
  align-items: center;
}

.picker-display {
  width: 100%;
  color: #4a5568;
  font-size: 15px;
}

.picker-display:empty::before {
  content: attr(placeholder);
  color: #9ca3af;
}

.form-textarea {
  resize: vertical;
  min-height: 120px;
}

.image-upload-container {
  margin-top: 8px;
}

.image-upload-area {
  width: 100%;
  min-height: 120px;
  border: 2px dashed #e2e8f0;
  border-radius: 12px;
  display: flex;
  align-items: center;
  justify-content: center;
  cursor: pointer;
  transition: all 0.2s ease;
  background: #f8fafc;
}

.image-upload-area:hover {
  border-color: #6366f1;
  background: #f0f4ff;
}

.upload-placeholder {
  text-align: center;
  color: #9ca3af;
}

.upload-placeholder i {
  font-size: 32px;
  margin-bottom: 8px;
  display: block;
}

.upload-placeholder p {
  margin: 4px 0;
  font-size: 14px;
}

.image-preview-container {
  display: grid;
  grid-template-columns: repeat(2, 1fr);
  gap: 12px;
  margin-top: 16px;
}

.image-preview-item {
  position: relative;
  width: 100%;
  height: 80px;
  border-radius: 8px;
  overflow: hidden;
}

.image-preview-item img {
  width: 100%;
  height: 100%;
  object-fit: cover;
}

.delete-btn {
  position: absolute;
  top: 4px;
  right: 4px;
  width: 24px;
  height: 24px;
  background: rgba(0, 0, 0, 0.6);
  color: white;
  border-radius: 50%;
  display: flex;
  align-items: center;
  justify-content: center;
  cursor: pointer;
  font-size: 14px;
}

.map-form-group {
  margin-bottom: 20px;
  /* #ifdef APP-PLUS */
  display: block;
  width: 100%;
  overflow: visible;
  /* #endif */
}

.map-container {
  border: 1px solid #e2e8f0;
  border-radius: 12px;
  overflow: hidden;
  position: relative;
  /* #ifdef APP-PLUS */
  z-index: 0;
  overflow: visible;
  /* #endif */
}

.map {
  width: 100%;
  height: 220px;
  background: #f8fafc;
  /* #ifdef APP-PLUS */
  position: relative !important;
  overflow: visible !important;
  min-height: 220px !important;
  /* #endif */
}

/* #ifdef APP-PLUS */
.map-wrapper {
  position: relative;
  width: 100%;
  height: 100%;
  pointer-events: none;
}
/* #endif */

.coordinates {
  padding: 12px 16px;
  background: #f8fafc;
  display: flex;
  justify-content: space-between;
  font-size: 14px;
  color: #4a5568;
}

.locate-btn {
  width: 100%;
  height: 48px;
  background: linear-gradient(135deg, #6366f1 0%, #8b5cf6 100%);
  color: white;
  border: none;
  border-radius: 12px;
  font-size: 15px;
  font-weight: 500;
  cursor: pointer;
  transition: all 0.2s ease;
  margin-top: 8px;
}

.locate-btn:hover {
  transform: scale(0.98);
}

.location-section {
  margin-bottom: 20px;
}

.location-select {
  display: flex;
  flex-direction: column;
  gap: 12px;
}

.autocomplete-suggestions {
  list-style: none;
  padding: 0;
  margin: 8px 0 0 0;
  border: 1px solid #e2e8f0;
  border-radius: 8px;
  background: white;
  max-height: 200px;
  overflow-y: auto;
}

.autocomplete-suggestions li {
  padding: 12px 16px;
  cursor: pointer;
  border-bottom: 1px solid #f1f5f9;
  font-size: 14px;
  color: #4a5568;
}

.autocomplete-suggestions li:hover {
  background: #f8fafc;
}

.autocomplete-suggestions li:last-child {
  border-bottom: none;
}

.ai-analysis-section {
  margin-bottom: 20px;
}

.gradient-btn1 {
  width: 100%;
  height: 48px;
  background: linear-gradient(135deg, #6366f1 0%, #8b5cf6 100%);
  color: white;
  border: none;
  border-radius: 12px;
  font-size: 15px;
  font-weight: 500;
  cursor: pointer;
  transition: all 0.2s ease;
  display: flex;
  align-items: center;
  justify-content: center;
  gap: 8px;
}

.gradient-btn1:hover:not(:disabled) {
  transform: scale(0.98);
}

.gradient-btn1:disabled {
  opacity: 0.6;
  cursor: not-allowed;
}

.btn-icon {
  font-size: 18px;
}

.spinner {
  width: 20px;
  height: 20px;
  border: 2px solid rgba(255, 255, 255, 0.3);
  border-top: 2px solid white;
  border-radius: 50%;
  animation: spin 1s linear infinite;
}

.ai-analysis-window {
  margin-top: 16px;
  padding: 16px;
  background: #f8fafc;
  border-radius: 12px;
  border: 1px solid #e2e8f0;
  max-height: 40vh;
  overflow-y: auto;
}

.ai-analysis-window h3 {
  color: #4a5568;
  font-size: 16px;
  margin-bottom: 12px;
}

.analysis-results {
  margin-top: 16px;
  display: flex;
  flex-direction: column;
  gap: 12px;
}

.result-item {
  display: flex;
  flex-direction: column;
  gap: 8px;
}

.result-item label {
  font-size: 14px;
  color: #4a5568;
  font-weight: 500;
}

.error-message {
  color: #ff4d4f;
  font-size: 12px;
  margin-top: 4px;
}

.readonly-input {
  background-color: #f8fafc !important;
  color: #6b7280 !important;
  cursor: not-allowed !important;
  border-color: #d1d5db !important;
}

.disabled-input {
  background-color: #f3f4f6 !important;
  color: #9ca3af !important;
  cursor: not-allowed !important;
  border-color: #d1d5db !important;
  opacity: 0.7 !important;
}

.floating-analysis-modal {
  position: fixed;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
  background: rgba(0, 0, 0, 0.5);
  display: flex;
  align-items: center;
  justify-content: center;
  z-index: 1000;
}

.analysis-modal-content {
  width: 90%;
  max-width: 320px;
  background: white;
  border-radius: 16px;
  padding: 24px;
  text-align: center;
}

.analysis-modal-header h3 {
  color: #4a5568;
  font-size: 18px;
  margin-bottom: 8px;
}

.analysis-stage {
  color: #9ca3af;
  font-size: 14px;
}

.analysis-progress-circle {
  margin: 20px 0;
  display: flex;
  justify-content: center;
}

.progress-circle {
  width: 80px;
  height: 80px;
  border-radius: 50%;
  background: conic-gradient(#6366f1 calc(var(--progress) * 1%), #e2e8f0 0);
  display: flex;
  align-items: center;
  justify-content: center;
  position: relative;
}

.progress-circle::before {
  content: '';
  position: absolute;
  width: 60px;
  height: 60px;
  background: white;
  border-radius: 50%;
}

.progress-text {
  position: relative;
  z-index: 1;
  color: #4a5568;
  font-size: 16px;
  font-weight: 500;
}

.analysis-countdown {
  color: #9ca3af;
  font-size: 14px;
}

.company-info {
  margin: 20px 0;
  padding: 20px;
  background: linear-gradient(135deg, #f8fafc 0%, #f1f5f9 100%);
  border-radius: 16px;
  border: 1px solid #e2e8f0;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.05);
}

.company-info h2 {
  color: #4a5568;
  font-size: 18px;
  margin-bottom: 16px;
  text-align: center;
  font-weight: 600;
}

.publish-btn {
  width: 100%;
  height: 48px;
  background: linear-gradient(135deg, #6366f1 0%, #8b5cf6 100%);
  color: white;
  border: none;
  border-radius: 12px;
  font-size: 16px;
  font-weight: 500;
  cursor: pointer;
  transition: all 0.2s ease;
  margin-top: 20px;
  position: relative;
  z-index: 10;
  -webkit-tap-highlight-color: transparent;
}

.publish-btn:hover {
  transform: scale(0.98);
}

.publish-btn.disabled {
  opacity: 0.6;
  cursor: not-allowed;
  background: #9ca3af;
}

.publish-btn.disabled:hover {
  transform: none;
}

.publish-section {
  margin-top: 20px;
}

.login-reminder {
  text-align: center;
  color: #9ca3af;
  font-size: 14px;
  margin-top: 12px;
  padding: 8px;
  background: #f8fafc;
  border-radius: 8px;
}

.auth-status-section {
  margin-bottom: 16px;
}

.auth-status-item {
  display: flex;
  align-items: center;
  gap: 12px;
  margin-bottom: 12px;
  padding: 12px;
  background: white;
  border-radius: 12px;
  border: 1px solid #e2e8f0;
}

.auth-status-item label {
  font-size: 14px;
  color: #4a5568;
  font-weight: 500;
  min-width: 70px;
}

.auth-status-display {
  flex: 1;
  font-size: 14px;
  padding: 8px 12px;
  border-radius: 8px;
  font-weight: 500;
  text-align: center;
}

.auth-status-display.authenticated {
  background-color: #d1fae5;
  color: #059669;
  border: 1px solid #a7f3d0;
}

.auth-status-display.warning {
  background-color: #fef3c7;
  color: #d97706;
  border: 1px solid #fcd34d;
}

.refresh-btn {
  width: 36px;
  height: 36px;
  background: linear-gradient(135deg, #f8fafc 0%, #e2e8f0 100%);
  border: 1px solid #cbd5e1;
  border-radius: 8px;
  display: flex;
  align-items: center;
  justify-content: center;
  cursor: pointer;
  transition: all 0.2s ease;
  padding: 0;
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.05);
}

.refresh-btn:hover {
  background: linear-gradient(135deg, #f0f4ff 0%, #dbeafe 100%);
  border-color: #6366f1;
  transform: scale(1.05);
  box-shadow: 0 4px 8px rgba(99, 102, 241, 0.2);
}

.refresh-btn:active {
  transform: scale(0.95);
}

.refresh-icon {
  font-size: 16px;
  color: #6366f1;
  transition: transform 0.3s ease;
}

.refresh-btn:hover .refresh-icon {
  transform: rotate(180deg);
}

.auth-warning {
  background: linear-gradient(135deg, #fff7ed 0%, #fed7aa 100%);
  color: #c2410c;
  padding: 16px;
  border-radius: 12px;
  margin-top: 12px;
  font-size: 13px;
  display: flex;
  flex-direction: column;
  gap: 16px;
  align-items: center;
  border: 1px solid #fdba74;
  box-shadow: 0 2px 8px rgba(251, 146, 60, 0.2);
}

.auth-warning .warning-text {
  font-weight: 600;
  text-align: center;
  margin-bottom: 8px;
  font-size: 14px;
}

.company-auth-btn {
  width: 100%;
  max-width: 200px;
  height: 44px;
  background: linear-gradient(135deg, #dc2626 0%, #ea580c 100%);
  color: white;
  border: none;
  border-radius: 10px;
  font-size: 14px;
  font-weight: 600;
  display: flex;
  align-items: center;
  justify-content: center;
  gap: 8px;
  cursor: pointer;
  transition: all 0.2s ease;
  box-shadow: 0 4px 12px rgba(220, 38, 38, 0.3);
}

.company-auth-btn:hover {
  transform: scale(0.98);
  box-shadow: 0 6px 16px rgba(220, 38, 38, 0.4);
}

.company-auth-btn:active {
  transform: scale(0.95);
}

.btn-icon {
  font-size: 16px;
}

.quick-login-tips {
  background: #f0f9ff;
  border: 1px solid #bae6fd;
  border-radius: 6px;
  padding: 8px 12px;
  margin-top: 8px;
}

.quick-login-tips .tips-text {
  color: #0369a1;
  font-size: 12px;
  line-height: 1.4;
}

.floating-progress {
  position: fixed;
  bottom: 0;
  left: 0;
  width: 100%;
  background: white;
  border-radius: 16px 16px 0 0;
  box-shadow: 0 -4px 16px rgba(0, 0, 0, 0.1);
  z-index: 1000;
  max-height: 120px;
  overflow: hidden;
}

.progress-header {
  padding: 16px;
  display: flex;
  align-items: center;
  justify-content: space-between;
  border-bottom: 1px solid #e2e8f0;
}

.progress-header h3 {
  color: #4a5568;
  font-size: 16px;
  margin: 0;
}

.progress-status {
  display: flex;
  align-items: center;
  gap: 8px;
  color: #9ca3af;
  font-size: 14px;
}

.status-indicator {
  width: 8px;
  height: 8px;
  background: #6366f1;
  border-radius: 50%;
  animation: pulse 2s infinite;
}

.close-btn {
  width: 36px;
  height: 36px;
  background: none;
  border: none;
  color: #9ca3af;
  cursor: pointer;
  display: flex;
  align-items: center;
  justify-content: center;
}

.progress-bar-container {
  height: 4px;
  background: #e2e8f0;
  overflow: hidden;
}

.progress-bar {
  height: 100%;
  background: linear-gradient(135deg, #6366f1 0%, #8b5cf6 100%);
  transition: width 0.3s ease;
}

.progress-details {
  max-height: 200px;
  overflow-y: auto;
  padding: 16px;
}

.progress-item {
  display: flex;
  align-items: center;
  gap: 12px;
  padding: 8px 0;
  border-bottom: 1px solid #f1f5f9;
}

.progress-item:last-child {
  border-bottom: none;
}

.progress-icon {
  width: 32px;
  height: 32px;
  background: #f8fafc;
  border-radius: 50%;
  display: flex;
  align-items: center;
  justify-content: center;
  color: #6366f1;
}

.progress-content {
  flex: 1;
}

.progress-message {
  color: #4a5568;
  font-size: 14px;
  margin-bottom: 4px;
}

.progress-time {
  color: #9ca3af;
  font-size: 12px;
}

.latest-badge {
  background: #6366f1;
  color: white;
  padding: 2px 8px;
  border-radius: 8px;
  font-size: 10px;
}

.hidden {
  display: none;
}

@keyframes spin {
  0% { transform: rotate(0deg); }
  100% { transform: rotate(360deg); }
}

@keyframes pulse {
  0%, 100% { opacity: 1; }
  50% { opacity: 0.5; }
}

@keyframes bubble-rise {
  0% {
    transform: translateY(100vh) scale(1);
    opacity: 0;
  }
  100% {
    transform: translateY(-20vh) scale(1.5);
    opacity: 0;
  }
}

/* 响应式适配 */
@media (max-width: 360px) {
  .container {
    padding: 12px;
  }
  
  .publish-form {
    padding: 16px;
  }
  
  .publish-form .page-title {
    font-size: 20px;
  }
  
  .form-input, .form-textarea, .form-select {
    font-size: 14px;
  }
  
  .map {
    height: 200px;
  }
  
  .form-group {
    margin-bottom: 12px;
  }
}

@media (min-width: 361px) and (max-width: 480px) {
  .map {
    height: 220px;
  }
}

@media (min-width: 481px) {
  .container {
    max-width: 480px;
    margin: 0 auto;
  }
  
  .map {
    height: 250px;
  }
}
</style>